<?php
namespace app\models\auth_app\msg\douyin;

use app\models\AuthAccount;
use app\models\AuthMessage;
use app\models\AuthUser;
use Yii;
use app\components\Func;

/**
 * webhook私信".
 * {
"event": "receive_msg",
"client_key": "awozt4qz86gzwka8",
"from_user_id": "edd2ac89-f044-484c-af09-0f6fbb8ebf77",
"to_user_id": "afe48e12-9568-4e76-b71d-47473dbee26b",
"content": {
    "message_type": "text",
    "text": "这有游戏内部号来玩玩嘛"
}
}
 */
class Receivemsg extends \app\models\AuthAppMsg
{
    public function run(){
        $msg_arr = json_decode($this->content, 1);
        $authAccount = AuthAccount::getObjByOpenId($msg_arr['to_user_id']);
        if(empty($authAccount))return ;
        $otherUser = AuthUser::getObjAddByOpenId($authAccount->auth_app_id,$authAccount->id,$msg_arr['from_user_id']);
        $authMessage = new AuthMessage();
        $authMessage->auth_app_id = $authAccount->auth_app_id;
        $authMessage->auth_account_id = $authAccount->id;
        $authMessage->auth_uid = $authAccount->app_uid;
        $authMessage->other_uid = $otherUser->id;
        $authMessage->is_send = 2;
        $authMessage->content = json_encode($msg_arr['content'],JSON_UNESCAPED_UNICODE);
        $authMessage->ctime = time();
        if(!$authMessage->save()){
            throw new \Exception(json_encode($authMessage->getErrors(),JSON_UNESCAPED_UNICODE),2000);
        }
        //推送新消息
        AuthAccount::pushNewMsg($authAccount->uid,AuthAccount::NEW_MSG_TYPE_MESSAGE);

        return json_encode($msg_arr['content']);
    }
}
